#include <iostream>
#include <boost/beast.hpp>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>

namespace beast = boost::beast;
namespace http = beast::http;
namespace websocket = beast::websocket;
namespace net = boost::asio;
namespace ssl = boost::asio::ssl;
using tcp = boost::asio::ip::tcp;

using namespace std;

// 处理WebSocket请求
void handleWebSocket(websocket::stream<beast::tcp_stream> &ws)
{
    try
    {
        // 接收消息
        beast::flat_buffer buffer;
        ws.read(buffer);

        // 只处理文本消息
        if (ws.got_text())
        {
            string message = boost::beast::buffers_to_string(buffer.data());
            cout << "Received message: " << message << endl;

            // 发送HelloWorld给前端
            string response = "HelloWorld";
            ws.text(true);
            ws.write(net::buffer(response));
        }
    }
    catch (const exception &e)
    {
        cerr << "WebSocket error: " << e.what() << endl;
    }
}

int main()
{
    // 初始化Boost库
    net::io_context ioc;

    // 创建TCP监听
    tcp::acceptor acceptor(ioc, {tcp::v4(), 9090});

    while (true)
    {
        // 等待并接受新连接
        tcp::socket socket(ioc);
        acceptor.accept(socket);

        // 构建WebSocket流
        websocket::stream<beast::tcp_stream> ws(move(socket));

        // WebSocket握手
        ws.accept();

        // 处理WebSocket请求
        handleWebSocket(ws);
    }

    return 0;
}